#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project ：pythonProject2 
@File    ：flask_use_id.py
@Author  ：beibei
@Date    ：2023/12/26 3:07 PM 
'''

'''
 （前置部署redis）基于flask和redis实现消息临时存储服务，
 协议 /pull{'userId': 'b'} /push {'userId': 'a', 'data': 'abc'}

'''
'''
1.缺点
没有做高并发的场景验证，如果有人在请求8999：http://118.25.152.242:8999/pull?userId=1，那么占用空间会内存溢出


'''
from flask import Flask, request, jsonify
import redis
import json

app = Flask(__name__)
db = []

redis_conn = redis.Redis(
    host='127.0.0.1',
    port=6379,
    db=8,
    password='8948lulu'
)


@app.route('/push', methods=['POST'])
def push_message():
    json_data = request.json
    userId = json_data['userId']
    data = json_data['data']
    # 实现的是用户隔离
    # data_list =[]
    # 查询redis中的数据
    redis_res = redis_conn.get(userId)
    # redis中的数据不为空，提取消息data的值
    if redis_res is not None:
        data_list = json.loads(redis_res.decode('utf-8'))
    else:
        data_list = []
    data_list.append(data)
    redis_conn.set(userId, json.dumps(data_list), ex=300)
    return jsonify({'msg': 'push message success'}), 200


@app.route('/pull', methods=['GET'])
def pull_message():
    json_data = request.args
    userId = json_data['userId']
    redis_res = redis_conn.get(userId)
    if redis_res is not None:
        data_list = json.dumps(redis_res.decode('utf-8'))
        redis_conn.delete(userId)
    else:
        data_list = []

    return jsonify({'msg': 'pull message success', 'data': data_list}), 200


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8999, debug=True)
